package bg.btanev.eightyfour.dao.exception;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author B.Tanev
 *
 */
public class DependentObjectExpection extends RuntimeException {
	/**
	 *
	 */
	private static final long serialVersionUID = -5791278806514916446L;

	private static final String MESSAGES_BUNDLE_NAME = "constraintViolationMessages";

	protected static final Logger logger = LoggerFactory.getLogger(DependentObjectExpection.class);

	private static ResourceBundle constraintMessages;
	static {
		try {
			constraintMessages = ResourceBundle.getBundle(MESSAGES_BUNDLE_NAME);
		} catch (MissingResourceException e) {
			constraintMessages = null;
			logger.warn("Cannot load constraint messages. Now constraint names will be dispalyed.", e);
		}
	}

	public DependentObjectExpection(ConstraintViolationException e) {
		super(getValueForKey(createMessageKey(e.getConstraintName())), e);
	}

	private static String createMessageKey(String fullConstraintName) {
		return fullConstraintName.substring(fullConstraintName.lastIndexOf('.') + 1);
	}

	private static String getValueForKey(String messageKey) {
		if (constraintMessages != null) {
			try {
				return constraintMessages.getString(messageKey);
			} catch (MissingResourceException e) {
				// Do nothing just return the default value.
			}
		}
		return String.format("ConstraintName: '%s'. Sorry no detail messages available.", messageKey);
	}

}
